import { CraftingSystem } from './CraftingSystem';
import { CraftingGrid } from './types';
import { BlockType } from '@/blocks/types';
import { BASIC_RECIPES } from './recipes';

export class RecipeValidator {
  private craftingSystem: CraftingSystem;

  constructor() {
    this.craftingSystem = new CraftingSystem();
  }

  public validateAllRecipes(): { valid: number; invalid: string[] } {
    const results = { valid: 0, invalid: [] as string[] };

    for (const recipe of BASIC_RECIPES) {
      try {
        const testGrid = this.createTestGrid(recipe);
        const result = this.craftingSystem.checkRecipe(testGrid);
        
        if (result && result.canCraft && result.recipe.id === recipe.id) {
          results.valid++;
          console.log(`✅ 配方 "${recipe.id}" 验证成功`);
        } else {
          results.invalid.push(recipe.id);
          console.error(`❌ 配方 "${recipe.id}" 验证失败`);
        }
      } catch (error) {
        results.invalid.push(recipe.id);
        console.error(`❌ 配方 "${recipe.id}" 验证出错:`, error);
      }
    }

    return results;
  }

  private createTestGrid(recipe: any): CraftingGrid {
    const grid: CraftingGrid = [];
    
    // 创建3x3空网格
    for (let row = 0; row < 3; row++) {
      grid[row] = [];
      for (let col = 0; col < 3; col++) {
        grid[row][col] = { type: null, count: 0 };
      }
    }

    // 根据配方类型填充测试网格
    if (recipe.type === 'shaped') {
      const patternHeight = recipe.pattern.length;
      const patternWidth = recipe.pattern[0]?.length || 0;
      
      // 将配方模式放在网格的左上角
      for (let row = 0; row < patternHeight && row < 3; row++) {
        for (let col = 0; col < patternWidth && col < 3; col++) {
          const blockType = recipe.pattern[row][col];
          if (blockType !== null) {
            grid[row][col] = { type: blockType, count: 1 };
          }
        }
      }
    } else if (recipe.type === 'shapeless') {
      // 对于无形状配方，将所有材料放在网格中
      let gridIndex = 0;
      for (const row of recipe.pattern) {
        for (const blockType of row) {
          if (blockType !== null && gridIndex < 9) {
            const gridRow = Math.floor(gridIndex / 3);
            const gridCol = gridIndex % 3;
            grid[gridRow][gridCol] = { type: blockType, count: 1 };
            gridIndex++;
          }
        }
      }
    }

    return grid;
  }

  public testSpecificRecipe(recipeId: string): boolean {
    const recipe = BASIC_RECIPES.find(r => r.id === recipeId);
    if (!recipe) {
      console.error(`配方 "${recipeId}" 不存在`);
      return false;
    }

    try {
      const testGrid = this.createTestGrid(recipe);
      const result = this.craftingSystem.checkRecipe(testGrid);
      
      if (result && result.canCraft && result.recipe.id === recipe.id) {
        console.log(`✅ 配方 "${recipeId}" 测试成功`);
        console.log(`结果: ${result.recipe.result.count}x ${this.getBlockName(result.recipe.result.type)}`);
        return true;
      } else {
        console.error(`❌ 配方 "${recipeId}" 测试失败`);
        return false;
      }
    } catch (error) {
      console.error(`❌ 配方 "${recipeId}" 测试出错:`, error);
      return false;
    }
  }

  private getBlockName(blockType: BlockType): string {
    const names: Partial<Record<BlockType, string>> = {
      [BlockType.AIR]: '空气',
      [BlockType.GRASS]: '草方块',
      [BlockType.DIRT]: '泥土',
      [BlockType.STONE]: '石头',
      [BlockType.LOG]: '原木',
      [BlockType.PLANKS]: '木板',
      [BlockType.COAL_ORE]: '煤矿',
      [BlockType.LAVA]: '岩浆',
      [BlockType.FURNACE]: '熔炉',
      [BlockType.TORCH]: '火把',
      [BlockType.CRAFTING_TABLE]: '工作台'
    };
    return names[blockType] || '未知方块';
  }

  public printRecipeInfo(recipeId: string): void {
    const recipe = BASIC_RECIPES.find(r => r.id === recipeId);
    if (!recipe) {
      console.error(`配方 "${recipeId}" 不存在`);
      return;
    }

    console.log(`\n=== 配方信息: ${recipe.id} ===`);
    console.log(`类型: ${recipe.type === 'shaped' ? '有形状' : '无形状'}`);
    console.log(`结果: ${recipe.result.count}x ${this.getBlockName(recipe.result.type)}`);
    console.log('材料模式:');
    
    recipe.pattern.forEach((row, rowIndex) => {
      const rowStr = row.map(item => 
        item === null ? '[ ]' : `[${this.getBlockName(item).charAt(0)}]`
      ).join(' ');
      console.log(`  ${rowStr}`);
    });
  }

  public listAllRecipes(): void {
    console.log('\n=== 所有可用配方 ===');
    BASIC_RECIPES.forEach(recipe => {
      console.log(`${recipe.id}: ${recipe.result.count}x ${this.getBlockName(recipe.result.type)}`);
    });
  }
}